import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  View,
  StyleSheet,
  TouchableOpacity,
  Text,
  StatusBar,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Icon from 'react-native-vector-icons/Ionicons';
import WebAmap from '../components/WebAmap';
import Compass from '../modules/CompassModule';
import { COLORS, SHADOWS } from '../styles/constants';

/**
 * 地图页面
 * 显示完整的地图视图
 */
export default function MapScreen({ route, navigation }) {
  const insets = useSafeAreaInsets();
  const { city, region, attractions, currentLocation: initialLocation } = route.params || {};
  
  // 实时位置和方向状态
  const [currentLocation, setCurrentLocation] = useState(initialLocation);
  const [heading, setHeading] = useState(0);
  const [compassEnabled, setCompassEnabled] = useState(false); // 罗盘开关状态
  const headingWatchId = useRef(null);
  const lastHeadingUpdateTime = useRef(0);
  const lastHeadingRef = useRef(null);

  // 启动实时罗盘监听
  const startHeadingWatch = useCallback(async () => {
    try {
      const isAvailable = await Compass.isAvailable();
      if (!isAvailable) {
        console.warn('[地图-罗盘] 设备不支持罗盘');
        return;
      }

      const subscription = Compass.startHeadingUpdates((data) => {
        const { heading: rawHeading } = data;
        if (typeof rawHeading === 'number' && rawHeading >= 0) {
          const now = Date.now();
          const current = rawHeading % 360;
          let nextHeading = current;

          if (typeof lastHeadingRef.current === 'number') {
            const prev = lastHeadingRef.current;
            let diff = current - prev;
            if (diff > 180) diff -= 360;
            if (diff < -180) diff += 360;

            if (Math.abs(diff) < 5) return;

            const alpha = 0.25;
            const filtered = prev + diff * alpha;
            nextHeading = (filtered + 360) % 360;
          }

          if (now - lastHeadingUpdateTime.current > 250) {
            const rounded = Math.round(nextHeading);
            setHeading(rounded);
            lastHeadingUpdateTime.current = now;
            lastHeadingRef.current = rounded;
          }
        }
      });
      headingWatchId.current = subscription;
    } catch (error) {
      console.error('[地图-罗盘] 启动失败:', error);
    }
  }, []);

  // 停止实时罗盘监听
  const stopHeadingWatch = useCallback(() => {
    if (headingWatchId.current) {
      Compass.stopHeadingUpdates(headingWatchId.current);
      headingWatchId.current = null;
    }
  }, []);

  // 根据罗盘开关启动/停止监听
  useEffect(() => {
    if (compassEnabled) {
      startHeadingWatch();
    } else {
      stopHeadingWatch();
    }
    
    return () => {
      stopHeadingWatch();
    };
  }, [compassEnabled, startHeadingWatch, stopHeadingWatch]);

  // 切换罗盘开关
  const toggleCompass = useCallback(() => {
    setCompassEnabled(prev => !prev);
  }, []);

  const handleMarkerPress = (attraction) => {
    const itemData = attraction.raw || attraction;
    const areaType = itemData.areaType || 1;
    navigation.navigate('AttractionDetail', {
      attraction: itemData,
      itemType: areaType === 1 ? 'scenicArea' : 'scenicSpot',
      itemId: itemData.id || itemData.scenicAreaId,
      areaType: areaType,
    });
  };

  return (
    <View style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor="transparent" translucent />
      
      {/* 地图 - 全屏显示 */}
      <View style={styles.mapContainer}>
        <WebAmap
          city={city}
          region={region}
          attractions={attractions || []}
          currentLocation={currentLocation}
          heading={heading}
          onPressMarker={handleMarkerPress}
          style={styles.fullScreenMap}
        />
      </View>

      {/* 返回按钮 - 悬浮在地图上方 */}
      <View style={[styles.header, { paddingTop: insets.top + 12 }]}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => navigation.goBack()}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <Icon name="arrow-back" size={24} color="#111" />
        </TouchableOpacity>
        <Text style={styles.title}>{city || '地图'}</Text>
      </View>

      {/* 罗盘开关按钮 - 右上角 */}
      <View style={[styles.compassButtonContainer, { top: insets.top + 12 }]}>
        <TouchableOpacity
          style={[
            styles.compassButton,
            compassEnabled && styles.compassButtonActive
          ]}
          onPress={toggleCompass}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <Icon 
            name="compass-outline" 
            size={24} 
            color={compassEnabled ? '#1E90FF' : '#666'} 
          />
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background.card,
  },
  header: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    zIndex: 1000,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingBottom: 12,
  },
  backButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: COLORS.background.card,
    justifyContent: 'center',
    alignItems: 'center',
    ...SHADOWS.sm,
  },
  title: {
    fontSize: 18,
    fontWeight: '600',
    color: COLORS.text.primary,
    marginLeft: 16,
  },
  mapContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  fullScreenMap: {
    height: '100%',
    width: '100%',
    flex: 1,
  },
  compassButtonContainer: {
    position: 'absolute',
    right: 16,
    zIndex: 1000,
  },
  compassButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: COLORS.background.card,
    justifyContent: 'center',
    alignItems: 'center',
    ...SHADOWS.sm,
  },
  compassButtonActive: {
    backgroundColor: COLORS.primaryLight,
  },
});
